<template>
  <!-- <lay-layout class="example">
    <lay-header>header</lay-header>
    <lay-layout>
      <lay-side>
        <lay-menu></lay-menu>
      </lay-side>
      <lay-body>content</lay-body>
    </lay-layout>
  </lay-layout> -->

  <lay-layout class="example w100 h100">
    <lay-side :class="[collapse?'side-open':'side-close']">
      <lay-menus></lay-menus>
    </lay-side>
    <lay-layout style="width: calc(100% - 200px);">
      <lay-header>
        <div> <img src="@/assets/image/home/collapse.svg" alt="" class="collapse" @click="collapse_click"></div>
        <div class="menu-admin">
          <lay-menu theme="light">
            <lay-sub-menu>

              <template #title>
                <lay-icon type="layui-icon-username"></lay-icon>
                {{system.description}}
              </template>
              <lay-menu-item @click="userMsg">用户信息</lay-menu-item>
              <lay-menu-item @click="editPwd">修改密码</lay-menu-item>
              <lay-menu-item @click="logout">退出登录</lay-menu-item>
            </lay-sub-menu>
          </lay-menu>
        </div>
      </lay-header>
      <lay-body class="w100 " style="display: flex;flex-direction: column;">
        <div class="main-tab global-tab ">
          <!-- <lay-tab v-model="current11" :allow-close="true">
            <lay-tab-item id="-100" title="首页" :allow-close="false">
            </lay-tab-item> 
            <lay-tab-item :id="item.permissionId" :title="item.permissionName" v-for="item in tabMenu" :key="item.permissionId">
            </lay-tab-item>
          </lay-tab> -->

          <div class="w100 df ">
            <lay-tab :modelValue="current11" :allowClose="true" @change="to" @close="close">
              <!-- <lay-tab-item id="home" title="首页" :closable="false">
                <template #title>
                  <span :class="['dot',selectedKey=='home'?'dot-this':''] "></span>
                  {{ '首页' }}
                </template>
              </lay-tab-item> -->
              <template :key="tab.permissionId" v-for="tab in tabMenu">
                <lay-tab-item :id="tab" :title="tab.permissionName" :closable="true">
                  <template #title>
                    <span :class="['dot',selectedKey==tab.permissionId?'dot-this':''] "></span>
                    {{ tab.permissionName }}
                  </template>
                </lay-tab-item>
              </template>
            </lay-tab>
            <lay-dropdown>
              <lay-icon type="layui-icon-down" class="designer-last-icon tab-r-icon"></lay-icon>
              <template #content>
                <lay-dropdown-menu>
                  <lay-dropdown-menu-item @click="closeAll">关闭全部</lay-dropdown-menu-item>
                </lay-dropdown-menu>
                <!-- <lay-dropdown-menu> 
                  <lay-dropdown-menu-item @click="closeOther">关闭其他</lay-dropdown-menu-item>
                </lay-dropdown-menu>
                <lay-dropdown-menu>
                  <lay-dropdown-menu-item @click="closeCurrent">关闭当前</lay-dropdown-menu-item>
                </lay-dropdown-menu> -->
              </template>
            </lay-dropdown>
          </div>

        </div>
        <!-- <lay-tab v-model="current11" :allow-close="true">
          <lay-tab-item id="1" :title="item.title" v-for="(item,index) in menuTab" :key="index">
          </lay-tab-item>
       
        </lay-tab> -->
        <router-view>

        </router-view>

      </lay-body>

      <lay-layer v-model="editVisible" :area="['500px', '450px']" :btn="editBtn" title="修改密码" :shadeClose="false">
        <div style="padding: 20px 50px;">
          <lay-form :model="editFrom" ref="editFromRef" label-position="top" required :rules="editPwdRule">
            <lay-form-item label="请输入旧密码" prop="oldPasswd">
              <lay-input v-model="editFrom.oldPasswd" size="sm" type="password" password placeholder="请输入旧密码"></lay-input>
            </lay-form-item>
            <lay-form-item label="请输入新密码" prop="newPasswd">
              <lay-input v-model="editFrom.newPasswd" size="sm" placeholder="请输入新密码" type="password" password></lay-input>
            </lay-form-item>
            <lay-form-item label="请再次输入新密码" prop="againNewPasswd" :label-width="200">
              <lay-input v-model="editFrom.againNewPasswd" size="sm" placeholder="请再次输入新密码" type="password" password></lay-input>
            </lay-form-item>

          </lay-form>
        </div>
      </lay-layer>

      <lay-layer ref="isShowUserCenterRef" v-model="userVisible" title="用户信息" :area="['800px', '700px']" @close="user_close" :shadeClose="false" :closeBtn="isClickUser?'1':false">
        <div style="padding: 20px 50px;">

          <lay-form :model="userForm" ref="userFromRef" label-position="top" :rules="userRules">
            <lay-form-item label="性别" prop="gender" required>
              <lay-select v-model="userForm.gender" placeholder="请选择" style="width: 100%;" size="sm">
                <lay-select-option value="男" label="男"></lay-select-option>
                <lay-select-option value="女" label="女"></lay-select-option>
              </lay-select>
            </lay-form-item>
            <lay-form-item label="手机号" prop="phonenum" required>
              <lay-input v-model="userForm.phonenum" size="sm" placeholder="请再次输入新密码"></lay-input>
            </lay-form-item>
            <lay-form-item label="头像" prop="avatar">
              <lay-upload size="xs" @done="getUploadFile2" :url="uploadUrl" :headers="{'saToken':system.token}" :beforeUpload="beforeUpload">
                <template #preview>
                  <div class="easy-wrap" v-if="userForm.avatar">
                    <el-image v-if="userForm.avatar" style=" height: 60px; width:100px" :src="userForm.avatar" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[userForm.avatar]" fit="cover" />
                  </div>
                </template>
              </lay-upload> 
            </lay-form-item>

            <lay-form-item label="电子签名" prop="signBase" required>
              <div class="df ai-c">
                <el-image style=" height: 50px;width:100px " :src="userForm.signBase" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[userForm.signBase]" fit="cover" />
                <lay-button type="primary" size="xs" style="margin-left: 10px;" v-if="!isShowSign" @click="isShowSign = !isShowSign">签名</lay-button>
                <lay-button type="primary" size="xs" style="margin-left: 10px;" v-if="isShowSign" @click="signSave">确认</lay-button>
                <lay-button type="primary" size="xs" style="margin-left: 10px;" v-if="isShowSign" @click="clearsign">清除</lay-button>
              </div> 

              <div style="border:1px dashed #000;margin-top: 8px;" v-if="isShowSign">
                <vueEsign ref="esign" class="mySign" format="image/png" :width="800" :height="300" bgColor="#fff" :isCrop="''" :lineWidth="4" :lineColor="'#000'" />
              </div>

            </lay-form-item>

            <lay-form-item label="" prop="">
              <div class="df jc-sb">
                <div></div>
                <div>
                  <lay-button @click="user_enter(isShowSign)" size="sm" type="primary">确认</lay-button>
                </div>
              </div>

            </lay-form-item>

          </lay-form>
        </div>
      </lay-layer>

    </lay-layout>
  </lay-layout>
</template>
  
<script setup lang="ts">
import LayMenus from "@/components/Menu.vue";
import { useCounterStore } from "@/current";
import http from "@/http";
import { storeToRefs } from "pinia"; // cnpm i pinia --save  2.1.3
import { onMounted, nextTick, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { layer } from "@layui/layer-vue";
import vueEsign from "vue-esign";
import { uploadBaseURL } from "@/http";
import { ElNotification } from "element-plus";
const store = useCounterStore();
const { collapse, menuTab, system, tabMenu, selectedKey, openKeys6, newMmenuList, isShowUserCenterRef, userForm, userRules, userFromRef } = storeToRefs(store); //  数据
const { get_router, get_user_list, user_enter, get_now_router } = store;
const current11 = ref("1");

onMounted(() => {
  nextTick(() => {
    // console.log(userCenterRef.value.open());
    // isShowUserCenterRef.value = userCenterRef.value
    tabMenu.value = [newMmenuList.value[0].children[0]];
    popupMsg();

    // console.log(document.getElementById('#toAllowance'));
  });
});

const collapse_click = () => {
  collapse.value = !collapse.value;
};

const to = async (item) => {
  console.log(item);
  await get_now_router(item.permissionId);
  if (item === "home") {
    router.push("/home");
    selectedKey.value = item;
  } else {
    router.push(item.permissionUrl);
    selectedKey.value = item.permissionId;
    openKeys6.value.includes(item.permissionParentId) ? "" : openKeys6.value.push(item.permissionParentId);
  }
};

const close = (item) => {
  console.log(item);

  let prev = getPreviousItemById(tabMenu.value, item.permissionId);
  if (prev) {
    selectedKey.value = prev.permissionId;
    router.push(prev.permissionUrl);
  } else {
    // selectedKey.value = "home";
    // router.push("/home");
  }

  tabMenu.value = tabMenu.value.filter((ele: any) => ele.permissionId != item.permissionId);
};

//关闭全部
const closeAll = async() => {
  console.log(newMmenuList.value[0].children[0]);
  console.log(tabMenu.value);

  tabMenu.value = [newMmenuList.value[0].children[0]];
  router.push(newMmenuList.value[0].children[0].permissionUrl);
  openKeys6.value = newMmenuList.value[0].permissionId;
  selectedKey.value = newMmenuList.value[0].children[0].permissionId;

  await get_now_router(selectedKey.value);


  //  tabMenu.value = [];
  // if (newMmenuList.value[0] && newMmenuList.value[0].children.length > 0) {
  //     router.push(newMmenuList.value[0].children[0].permissionUrl);
  //     openKeys6.value = newMmenuList.value[0].permissionId;
  //     selectedKey.value =  newMmenuList.value[0].children[0].permissionId;
  //     tabMenu.value =newMmenuList.value[0].children[0]
  //   }
  // tabMenu.value = [];
  // router.push("/home");
  // selectedKey.value = "home";
};
function getPreviousItemById(arr, targetId) {
  console.log(arr, targetId);

  let currentIndex = -1; // 初始化索引为-1，表示未找到目标元素

  // 遍历数组查找目标元素的索引
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].permissionId === targetId) {
      currentIndex = i;
      break;
    }
  }

  // 如果没有找到目标元素，返回null
  if (currentIndex === -1) {
    return null;
  }

  // 计算上一条数据的索引
  const previousIndex = currentIndex - 1;

  // 如果上一条数据的索引有效，返回上一条数据，否则返回null
  return previousIndex >= 0 ? arr[previousIndex] : null;
}

const router = useRouter();

// 修改密码
const editVisible = ref(false);
// 修改密码校验
const editPwdRule = ref({
  newPasswd: {
    validator(rule, value, callback, source, options) {
      console.log(rule, value, value.length);

      let reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
      if (value.length < 8 || value.length > 18 || !reg.test(value)) {
        callback(new Error(`密码长度为8~18位 并且必须包含大小写`));
      } else {
        return true;
      }
    },
  },
  againNewPasswd: {
    validator(rule, value, callback, source, options) {
      // console.log(value);
      // console.log(editFrom.value.pass);
      // console.log(editFrom.value.pass != value);
      let reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
      if (value.length < 8 || value.length > 18 || !reg.test(value)) {
        callback(new Error(`密码长度为8~18位 并且必须包含大小写`));
      } else if (editFrom.value.newPasswd != value) {
        callback("两次密码输入不一致");
      } else {
        return true;
      }
      // if (value < 18) {
      //   callback(new Error(`${rule.field}太过于年轻`));
      // } else {
      //   return true;
      // }
    },
  },
});
const editFrom = ref({
  oldPasswd: "",
  newPasswd: "",
  againNewPasswd: "",
});
const editFromRef = ref();
const editPwd = async () => {
  editVisible.value = true;
  editFrom.value.oldPasswd = "";
  editFrom.value.newPasswd = "";
  editFrom.value.againNewPasswd = "";
};

const editBtn = ref([
  {
    text: "确认",
    callback: () => {
      editFromRef.value.validate(async (isValidate, model, errors) => {
        console.log(isValidate);

        if (isValidate) {
          const res = await http.corsApi("/secUser/updateUserPassword", "put", { ...editFrom.value });
          console.log(res);
          if (res.data) {
            editVisible.value = false;
            layer.msg("密码修改成功,请重新登录", { icon: 1, time: 2000 });
            router.push("/login");
            setTimeout(() => {
              window.location.reload();
            }, 1000);
          }
        }
      });
    },
  },
  {
    text: "取消",
    callback: () => {
      editVisible.value = false;
    },
  },
]);
// 退出登录
const logout = async () => {
  layer.confirm("确认要退出吗？", {
    title: "提示",
    btn: [
      {
        text: "确认",
        callback: async (id) => {
          const res = await http.corsApi(`/login/logoutByUserId/${system.value.id}`, "post", {
            userId: system.value.id,
          });
          console.log(res);
          if (res.data) {
            localStorage.clear();
            router.push("/login");
            layer.msg("退出成功", { time: 2000, icon: 1 });

            setTimeout(() => {
              window.location.reload();
            }, 200);
          }
          layer.close(id);
        },
      },
      {
        text: "取消",
        callback: (id) => {
          layer.close(id);
        },
      },
    ],
  });
};

const isShowSign = ref(false);
const userVisible = ref(false);
// const userForm = ref([]);
// const userRules = ref({
//   phonenum: {
//     validator(rule, value, callback, source, options) {
//       console.log(rule, value.length);

//       if (Number.isNaN(value * 1)) {
//         callback(new Error(`${rule.field}格式不正确`));
//       } else if (value.length !== 11) {
//         callback(new Error(`${rule.field}长度不正确`));
//       } else {
//         return true;
//       }
//     },
//   },
// });

const isClickUser = ref(false);
const userCenterRef = ref();
// 用户信息
const userMsg = async () => {
  get_user_list();
  // userVisible.value = true;

  isShowUserCenterRef.value.open();
  isClickUser.value = true;
};

const user_close = () => {
  isShowUserCenterRef.value.close();
};

const esign = ref();
// 保存
const signSave = () => {
  // 可选配置参数 ，在未设置format或quality属性时可在生成图片时配置 例如： {format:'image/jpeg', quality: 0.5}
  // this.$refs.esign.generate({format:'image/jpeg', quality: 0.5})
  console.log(111);

  esign.value
    .generate()
    .then((res) => {
      console.log(res);
      userForm.value.signBase = res;
      isShowSign.value = !isShowSign.value;
    })
    .catch((err) => {
      console.log(err);

      layer.msg("请在框内进行电子签名", { time: 2000, icon: 2 });
      // 画布没有签字时会执行这里 'Not Signned'
      //   this.$message.error("您还未完成签字，请签字完成后保存");
    });
};

const clearsign = () => {
  esign.value.reset();
};

// const userFromRef= ref()
// const userBtn= ref([
//   {
//     text: "确认",
//     callback: () => {
//       userFromRef.value.validate(async (isValidate, model, errors) => {
//         console.log(isValidate);

//         console.log(userForm.value);

//         const res = await http.corsApi("/secUser/modify", "put", { ...userForm.value });
//         console.log(res);
//         if (res.data) {
//           userVisible.value = false;
//           layer.msg("修改成功", { icon: 1, time: 2000 });

//         }
//       });
//     },
//   },
//   {
//     text: "取消",
//     callback: () => {
//       userVisible.value = false;
//     },
//   },
// ]);

const uploadUrl = ref(
  import.meta.env.DEV ? `/api/pc/minio/uploadSingleFileByFileOrBucketName?bucketName=${"smokeface"}` : uploadBaseURL + `/pc/minio/uploadSingleFileByFileOrBucketName?bucketName=${"smokeface"}`
);
// 文件上传
const getUploadFile2 = async (filelist) => {
  console.log(filelist);
  const data = filelist.data ? JSON.parse(filelist.data) : [];
  userForm.value.avatar = data.data;
  userForm.value.avatarBase = "";
  // const res = await http.corsApi(uploadUrl,'post',{file:filelist.data[0]})
  // console.log(res);
};

const beforeUpload = async (file) => {
  console.log(file);

  var isOver = true;
  if (file.size > 200000) { 
    isOver = false;
    layer.msg(`文件大小不得超过200k`, { icon: 2 });
  }
  return new Promise((resolver) => resolver(isOver));
};
 
// const get_user_list = async () => {
//   const res = await http.corsApi("/secUser/userDetail", "get", {});
//   console.log(res);
//   userForm.value = res.data;
// };

const popupMsg = async () => {
  const res = await http.corsApi("/allowance/popup", "get", {});
  console.log(res);
  if (res.data) {
    // router.push('/allowance')
    // selectedKey.value = 'allowance'
    let notification = ElNotification({
      title: "您有津贴尚未确认，请点击前往进行处理。",
      dangerouslyUseHTMLString: true,
      duration: 0,
      position: "bottom-right",
      customClass: "Notification-class",
      message: `<div>
        <strong></strong>
          <div style="width:100%;margin:20px 0 0 0   " class="df jc-sb">
           <div></div>
           <div> 
            <router-link to="/allowance" ><a style="background-color: #36b368;color:#fff; padding:8px 12px; cursor: pointer;" id="toAllowance">前往</a></router-link>
          
            </div>
          </div>
        </div>`,

      // <a style="padding:7px 12px;  border: 1px solid #d2d2d2; cursor: pointer;">取消</a>
    });

    document.getElementById("toAllowance").addEventListener("click", function (e) {
      e.preventDefault();
      console.log(11111);
      router.push("/allowance");
      selectedKey.value = "allowance";
      openKeys6.value = ["routine"];
      notification.close();
    });
  }
};

// 防止多次弹层出现
let isSign = ref(true);
watchEffect(async () => {
  console.log(newMmenuList.value);
  console.log(!newMmenuList.value);
  console.log(userForm.value);

  if (newMmenuList.value.length <= 0) {
    await get_router();
  }

  console.log(system.value);

  if (system.value && !system.value.signUrl && isSign) {
    isSign.value = false;
    console.log(121211111111111111);

    layer.msg("检测到您还未签名！ 请先进行签名", { time: 2000 });
    setTimeout(() => {
      isShowUserCenterRef.value.open();
    }, 2000);
  }
});
</script>

<style scoped lang="scss">
.layui-side {
  /*   border: 1px solid #bbbbbb; */
  box-sizing: border-box;
  // background: linear-gradient(#ecfcef, #ddf5fa);

  // :deep(.layui-nav .layui-this) {
  //   background-color: #7fdbb5;

  //   background: rgba(127, 219, 181, 0.322);
  //   span {
  //     color: #50daa0 !important;
  //     .layui-icon {
  //       color: #50daa0 !important;
  //     }
  //   }
  // }
}
.layui-header {
  // background: linear-gradient(to right, #eafbf1, #ddf5fa);
  /*  border: 1px solid #bbbbbb; */
  border-left: 0 none;
  box-sizing: border-box;
  height: 61px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0px 15px;

  .collapse {
    width: 28px;
    height: 28px;
  }
}

.side-open {
  flex: 0 0 200px;
  width: 200px;
}
.side-close {
  flex: 0 0 60px !important;
  width: 60px !important;
}

.layui-body {
  // padding: 35px 35px 8px 35px;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  // background-color: #f0f2f5;
  // background-color: #fafcfb;
  // background: linear-gradient(to right, #eafbf1, #ddf5fa);
}

.menu-admin {
  .layui-nav {
    background-color: transparent;
    color: #000;
    .layui-nav-more {
      color: #000;
    }
  }
}

.main-tab {
  background-color: #fff;
  box-sizing: border-box;
  .layui-tab {
    margin: 0;
  }
  :deep(.layui-tab-content) {
    display: none;
  }
  // :deep(.layui-this) {
  //   background-color: #16baaa;
  // }
}

.global-tab {
  width: 100%;
  display: flex;
  position: relative;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  border-top: 1px solid whitesmoke;
  z-index: 999;

  :deep(.layui-tab-title li) {
    color: #696969;
    font-size: 14px;
    line-height: 40px;
    border-right: 1px solid whitesmoke;
    border-bottom: none;
  }
}

.global-tab .layui-tab {
  flex-grow: 1;
  width: calc(100% - 40px);
}

.global-tab .layui-tab .layui-tab-bar {
  border: none;
  border-left: 1px solid whitesmoke;
}

.global-tab .layui-tab .layui-tab-bar.prev {
  border-left: none;
}

.global-tab > i {
  width: 40px;
  background: white;
  height: 100%;
  line-height: 40px;
  text-align: center;
  border-left: 1px solid whitesmoke;
}

.global-tab .layui-tab .dot {
  display: inline-block;
  background-color: whitesmoke;
  margin-right: 8px;
  border-radius: 50px;
  height: 8px;
  width: 8px;
}

.global-tab .layui-tab .layui-this .dot {
  background-color: var(--global-primary-color);
}

.global-tab .layui-tab .layui-tab-close:hover {
  background: transparent !important;
  color: #e2e2e2 !important;
}
.designer {
  display: flex;
  width: calc(100% - 15px);
  height: 37px;
  position: relative;
  font-size: 14px;
  color: dimgray;
  cursor: pointer;

  .layui-tab .layui-tab-bar {
    height: 32px;
    line-height: 32px;
    margin-top: 5px;
  }

  .layui-tab .layui-tab-bar.prev {
    border-left: none;
    height: 32px;
    line-height: 32px;
    margin-top: 5px;
  }

  box-shadow: unset;
  z-index: 999;
  .designer-tab {
    display: inline-block;
    flex-grow: 1;
    width: 100%;
    padding-left: 15px;
  }
  .designer-tab-item {
    display: inline-block;
    height: 32px !important;
    line-height: 32px !important;
    padding: 0px 10px;
    margin-top: 5px;
    background-color: #fff;
    border-radius: 4px;
    margin-right: 5px;
  }
  .dot {
    display: inline-block;
    background-color: whitesmoke;
    margin-right: 8px;
    border-radius: 50px;
    height: 8px;
    width: 8px;
  }

  .designer-close {
    position: relative;
    display: inline-block;
    width: 18px;
    height: 18px;
    line-height: 20px;
    margin-left: 8px;
    top: 1px;
    text-align: center;
    font-size: 14px;
    color: var(--global-neutral-color-8);
    transition: all 0.2s;
    -webkit-transition: all 0.2s;
  }
}
.dot-this {
  background-color: var(--global-primary-color) !important;
}
.designer-last-icon {
  width: 32px !important;
  height: 32px !important;
  background: white;
  margin-top: 5px;
  line-height: 32px !important;
  text-align: center;
  border-radius: 4px;
}

:deep(.el-image-viewer__img) {
  background-color: #fff;
}
</style> 


<style lang="scss" >
.Notification-class {
  .el-notification__group {
    width: 100%;
  }
}
</style>